package hot;

public class erwu {
//    https://leetcode.cn/problems/reverse-nodes-in-k-group/description/?envType=study-plan-v2&envId=top-100-liked
     static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }

        public static ListNode reverseKGroup(ListNode head, int k) {
            //先遍历链表中有多个节点
            ListNode cur=head;
            int n=0;
            while(cur!=null){
                n++;
                cur=cur.next;
            }
            cur=head;
            //求得要翻转几次
            n=n/k;
            //创建个虚拟头节点
            ListNode newHead=new ListNode(-1);
            ListNode newHead1=newHead;
            ListNode tmp=new ListNode(-1);
            //要翻转n次
            for(int i=0;i<n;i++){
                //每次翻转k个节点
                tmp=cur;
                int j=1;
                while(j<=k){
                    ListNode curN=cur.next;
                    cur.next=newHead.next;
                    newHead.next=cur;
                    cur=curN;
                    j++;
                }
                //走到这里 则说明第一次翻转已经翻转完
                newHead=tmp;
            }
            //走到这里 就说明 所有的都翻转完 没有翻转的就正常拼接就可以了
            tmp.next=cur;
            return  newHead1.next;
        }

    public static void main(String[] args) {
        ListNode head1=new ListNode(1);
        ListNode head2=new ListNode(2);
        ListNode head3=new ListNode(3);
        ListNode head4=new ListNode(4);
        ListNode head5=new ListNode(5);
        head1.next=head2;
        head2.next=head3;
        head3.next=head4;
        head4.next=head5;
        head5.next=null;
        ListNode result=reverseKGroup(head1,2);
    }

}
